package com.w4c.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest servletRequest = (HttpServletRequest) request;
		HttpServletResponse servletResponse = (HttpServletResponse) response;

		String requestedUri = servletRequest.getRequestURI();
		String contextPath = servletRequest.getContextPath();

		HttpSession session = servletRequest.getSession();

		if (session.getAttribute("userObj") == null) {
			if (requestedUri.equals(contextPath)
					|| requestedUri.equals(contextPath.concat("/"))
					|| requestedUri.toLowerCase().contains(".js")
					|| requestedUri.toLowerCase().contains(".css")
					|| requestedUri.toLowerCase().contains(".properties")
					|| requestedUri.toLowerCase().contains(".gif")
					|| requestedUri.toLowerCase().contains(".png")
					|| requestedUri.toLowerCase().contains(".jpg")
					|| requestedUri.toLowerCase().contains(".woff")) {
				chain.doFilter(request, response);
			} else {
				servletResponse.sendRedirect(contextPath);
			}
		} else {
			chain.doFilter(request, response);
		}

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

}
